package com.dyit.interceptor;

import com.dyit.exception.user.IncorrectPerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthorityInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) {
        System.out.println("--->"+request.getParameter("tocken"));
        System.out.println();
        /**
         *  gen ju qie ge uri huo qu fang fa
         *  gen ju fang fa ming bu tong zou bu tong de quan xian
         */
        String uri=request.getRequestURI();
        String requestMethod=uri.substring(uri.lastIndexOf("/")+1);
        /**
         * redisuserper:      缓存中的信息：用户权限
         * webuserper:  前端传过来的tocken：用户权限
         */
        Integer redisuserper= (Integer) redisTemplate.opsForValue().get("currentuserper");
        String webuserper=request.getParameter("tocken");

        if (redisuserper==null || webuserper==null){
            throw new IncorrectPerException("你还没有登陆!");
        }
        /**
         * 添加书的权限判断
         */
        if(requestMethod.equals("addBook")){
            if(webuserper=="2"){
                return false;
            }else {
                throw new IncorrectPerException("你的权限不够!");
            }
        }

        /**
         *查询所有图书的权限判断
         */
        if (response.equals("findAllBookByLibraryId")){
            if (webuserper=="1"){
                return false;
            }else {
                throw new IncorrectPerException("你不是用户!");
            }
        }

        return true;

    }
}
